<template>
  <view class="container" :style="{ backgroundImage: `url(${counterStore.bg_img})` }">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="back-button" @tap="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="page-title">AI解牌</text>
    </view>

    <!-- 顶部系统消息 -->
    <view class="system-message">
      <image class="avatar" src="/static/images/avatar.png" mode="aspectFit" />
      <view class="message-content">
        <text class="message-text">小程序已接入DeepSeek-R1满血版，点击输入框上的模型类型即可切换。</text>
        <text class="message-link">点击查看AI解析时间和费用</text>
      </view>
    </view>

    <!-- 充值提示消息 -->
    <view class="system-message">
      <image class="avatar" src="/static/images/avatar.png" mode="aspectFit" />
      <view class="message-content">
        <text class="message-text">为方便使用，小程序开通预充值服务。余额大于支付金额都将自动抵扣。</text>
        <text class="message-warning">注意：预充值无法退款，请清楚需充值！</text>
      </view>
    </view>

    <!-- 余额显示 -->
    <view class="balance-box">
      <text>当前余额：</text>
      <text class="amount">0元</text>
    </view>

    <!-- 充值选项 -->
    <view class="recharge-options">
      <view class="option" :class="{ active: selectedOption === '5' }" @tap="selectOption('5')">
        <text class="price">5¥</text>
        <text class="discount">9.6折</text>
      </view>
      <view class="option" :class="{ active: selectedOption === '10' }" @tap="selectOption('10')">
        <text class="price">10¥</text>
        <text class="discount">9.5折</text>
      </view>
      <view class="option" :class="{ active: selectedOption === '50' }" @tap="selectOption('50')">
        <text class="price">50¥</text>
        <text class="discount">9折</text>
      </view>
    </view>

    <!-- 充值按钮 -->
    <view class="recharge-btn" @tap="handleRecharge">
      充值
    </view>

    <!-- 卡牌展示区域 -->
    <view class="cards-section">
      <text class="section-title">下面是你凭感觉选中的{{cardCount}}张牌</text>
      <view class="cards-grid">
        <view v-for="(card, index) in selectedCards" :key="index" class="card-item">
          <image :src="card.image" mode="aspectFit" class="card-image" />
          <text class="card-position">{{ card.position === 'up' ? '正' : '逆' }}</text>
          <text class="card-name">{{ card.name }}</text>
        </view>
      </view>
    </view>

   
    <view class="model-selector">
    <view 
      class="model-option" 
      :class="{ active: selectedModel === 'deepseek' }" 
      @tap="selectModel('deepseek')"
    >
      deepseek
    </view>
    <view 
      class="model-option" 
      :class="{ active: selectedModel === 'wenxin' }" 
      @tap="selectModel('wenxin')"
    >
      文心一言
    </view>
  </view>

  <!-- 新增AI对话容器 -->
  <view class="chat-container" v-if="selectedModel">
    <view class="chat-box">
      <scroll-view 
        scroll-y 
        class="messages" 
        :scroll-into-view="lastMessageId"
        ref="messageContainer"
      >
        <view 
          v-for="(message, index) in messages"
          :id="'msg'+index"
          :key="index"
          :class="['message', message.role]"
        >
          <view class="message-content">
            {{ message.content }}
          </view>
        </view>
      </scroll-view>

      <view class="input-area">
        <input
          v-model="questionText"
          :placeholder="selectedModel === 'deepseek' ? '输入消息，按Enter发送...' : '请输入解牌问题'"
          class="chat-input"
          @confirm="sendMessage"
          :disabled="isLoading"
        />
        <button 
          @tap="sendMessage" 
          :disabled="isLoading || !questionText.trim()"
          class="send-btn"
        >
          {{ isLoading ? "发送中..." : "发送" }}
        </button>
      </view>
    </view>
  </view>
    
   
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed ,nextTick,onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {useCounterStore} from '@/store/counter'
import axios from 'axios'

const CHAT_STORAGE_KEY = 'ai_chat_history'
const counterStore = useCounterStore()
// 新增AI对话相关数据
const messages = ref<Array<{role: string, content: string}>>([])
const isLoading = ref(false)
const questionText = ref('')
const selectedModel = ref('')
const lastMessageId = ref('')
const messageContainer = ref(null)
const baseUrl = "http://127.0.0.1:8000"

// 选择模型
const selectModel = (model: string) => {
  selectedModel.value = model
  messages.value = [] // 清空消息历史
  // 添加欢迎消息
  messages.value.push({
    role: "assistant",
    content: model === 'deepseek' 
      ? "你好！我是AI助手，很高兴为你服务。"
      : "你好！我是文心一言，很高兴为您服务。"
  })
  uni.setStorageSync(CHAT_STORAGE_KEY, {
    messages: messages.value,
    selectedModel: selectedModel.value
  })
}

// 发送消息
const sendMessage = async () => {
  if (!questionText.value.trim() || isLoading.value) return

  // 添加用户消息
  messages.value.push({
    role: "user",
    content: questionText.value.trim()
  })

  const userMessage = questionText.value.trim()
  questionText.value = ""
  isLoading.value = true

  try {
    const url = selectedModel.value === 'deepseek' 
      ? `${baseUrl}/app/deepseek/chat/`
      : `${baseUrl}/app/wenxin/chat/`

    const requestData = selectedModel.value === 'deepseek'
      ? { message: userMessage, cards: selectedCards.value }
      : { question: userMessage, cards: selectedCards.value }

    const res = await uni.request({
      url,
      method: "POST",
      data: requestData,
      header: { "Content-Type": "application/json" }
    })

    if (res.data?.status === "success") {
      messages.value.push({
        role: "assistant",
        content: selectedModel.value === 'deepseek'
          ? res.data.response
          : res.data.response?.result || "收到空响应"
      })
    } else {
      messages.value.push({
        role: "assistant",
        content: res.data?.message || "请求失败"
      })
    }
  } catch (err) {
    console.error("Error:", err)
    messages.value.push({
      role: "assistant",
      content: "服务器连接失败"
    })
  } finally {
    isLoading.value = false
    uni.setStorageSync(CHAT_STORAGE_KEY, {
    messages: messages.value,
    selectedModel: selectedModel.value
  })
    await nextTick()
    scrollToBottom()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messages.value.length > 0) {
    lastMessageId.value = 'msg' + (messages.value.length - 1)
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    fail: (err) => {
      console.error('返回失败:', err)
      uni.showToast({
        title: '返回失败',
        icon: 'none'
      })
    }
  })
}

// 选中的充值选项
const selectedOption = ref('')

// 定义卡牌数据的类型
interface CardData {
  image: string
  name: string
  position: 'up' | 'down'
}

// 选中的卡牌数据
const selectedCards = ref<CardData[]>([])

// 计算选中的牌数
const cardCount = computed(() => selectedCards.value.length)

// 从上一个页面获取卡牌数据
onLoad((options: any) => {
  if (options.cards) {
    selectedCards.value = JSON.parse(decodeURIComponent(options.cards))
    console.log('从上个页面获取到的卡牌数据:', selectedCards.value)
  }
  // 默认选中 deepseek
  selectModel('deepseek')
  
  // 自动发送第一个问题
  if (selectedCards.value.length > 0) {
    const cardDescriptions = selectedCards.value.map(card => {
      const position = card.position === 'up' ? '正位' : '逆位'
      return `${card.name}(${position})`
    }).join('、')
    
    const initialQuestion = `我抽到了以下塔罗牌：${cardDescriptions}，请为我解析这些牌的含义。`
    
    // 设置问题并发送
    questionText.value = initialQuestion
    sendMessage()
  }
})

// 选择充值选项
const selectOption = (option: string) => {
  selectedOption.value = option
}

// 处理充值
const handleRecharge = () => {
  if (!selectedOption.value) {
    uni.showToast({
      title: '请选择充值金额',
      icon: 'none'
    })
    return
  }
  // TODO: 实现充值逻辑
}

onMounted(() => {
  uni.setStorageSync('img_list', selectedCards.value); // 推荐用同步方法避免异步问题
  uni.setStorageSync('ai_list',messages.value)
});
// 添加页面卸载时的清理函数
// onUnmounted(() => {
//   // 清除本地存储的消息
//   uni.removeStorageSync(CHAT_STORAGE_KEY)
// })
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(180deg, #1a1a2e 0%, #16213e 100%);
  padding: 0 4vw;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.navbar {
  height: 12vw;
  display: flex;
  align-items: center;
  position: relative;
  margin-bottom: 4vw;
}

.back-button {
  position: relative;
  width: 8vw;
  height: 8vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  border-radius: 50%;
}

.back-icon {
  color: #fff;
  font-size: 5vw;
}

.page-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  color: #fff;
  font-size: 4vw;
  font-weight: bold;
}

.system-message {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
  background: rgba(255, 255, 255, 0.1);
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.message-content {
  flex: 1;
}

.message-text {
  color: #fff;
  font-size: 28rpx;
  line-height: 1.5;
  margin-bottom: 10rpx;
  display: block;
}

.message-link {
  color: #27ba9b;
  font-size: 28rpx;
}

.message-warning {
  color: #ff6b6b;
  font-size: 28rpx;
}

.balance-box {
  background: rgba(255, 255, 255, 0.1);
  padding: 30rpx;
  border-radius: 16rpx;
  text-align: center;
  margin: 30rpx 0;
  color: #fff;
}

.amount {
  color: #27ba9b;
  font-weight: bold;
  margin-left: 10rpx;
}

.recharge-options {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  margin: 30rpx 0;
}

.option {
  flex: 1;
  background: rgba(255, 255, 255, 0.1);
  padding: 20rpx;
  border-radius: 16rpx;
  text-align: center;
  border: 2rpx solid transparent;
}

.option.active {
  border-color: #27ba9b;
  background: rgba(39, 186, 155, 0.1);
}

.price {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  display: block;
}

.discount {
  color: #27ba9b;
  font-size: 24rpx;
  margin-top: 10rpx;
  display: block;
}

.recharge-btn {
  background: linear-gradient(90deg, #27ba9b, #1f9d82);
  height: 88rpx;
  border-radius: 44rpx;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx auto;
  width: 60%;
}

.cards-section {
  margin: 40rpx 0;
}

.section-title {
  color: #fff;
  font-size: 28rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.cards-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  justify-content: center;
}

.card-item {
  width: 180rpx;
  position: relative;
}

.card-image {
  width: 100%;
  height: 280rpx;
  border-radius: 12rpx;
}

.card-position {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.card-name {
  color: #fff;
  font-size: 24rpx;
  text-align: center;
  margin-top: 10rpx;
}

.model-selector {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  margin: 30rpx 0;
}

.model-option {
  flex: 1;
  height: 80rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 24rpx;
}

.model-option.active {
  background: rgba(39, 186, 155, 0.2);
  color: #27ba9b;
}

.question-input {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 40rpx;
}

.question-input input {
  flex: 1;
  height: 60rpx;
  color: #fff;
  font-size: 28rpx;
}

.input-placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.ai-button {
  background: #27ba9b;
  padding: 10rpx 30rpx;
  border-radius: 30rpx;
  color: #fff;
  font-size: 28rpx;
}

.chat-container {
  margin: 20rpx 0;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16rpx;
  overflow: hidden;
}

.chat-box {
  display: flex;
  flex-direction: column;
  min-height: 200rpx;
}

.messages {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
  max-height: 800rpx; /* 设置最大高度,避免内容过多时占满屏幕 */
}

.message {
  margin: 20rpx;
  max-width: 80%;
  animation: fadeIn 0.3s ease;
}

.message.user {
  margin-left: auto;
}

.message.assistant {
  margin-right: auto;
}

.message-content {
  padding: 15rpx 20rpx;
  border-radius: 16rpx;
  color: #fff;
  font-size: 28rpx;
  line-height: 1.5;
  word-break: break-word;
  white-space: pre-wrap;
}

.user .message-content {
  background: #27ba9b;
  border-radius: 16rpx 16rpx 4rpx 16rpx;
}

.assistant .message-content {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 16rpx 16rpx 16rpx 4rpx;
}

.input-area {
  padding: 20rpx;
  border-top: 1rpx solid rgba(255, 255, 255, 0.1);
  display: flex;
  gap: 20rpx;
  align-items: flex-end;
}

.chat-input {
  flex: 1;
  min-height: 80rpx;
  max-height: 120rpx;
  padding: 15rpx 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 40rpx;
  color: #fff;
  font-size: 28rpx;
}

textarea.chat-input {
  resize: none;
}

.send-btn {
  width: 160rpx;
  height: 80rpx;
  background: #27ba9b;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:disabled {
  opacity: 0.6;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20rpx); }
  to { opacity: 1; transform: translateY(0); }
}
</style>